package ar.edu.unlu.sistemas.p2p.business.file;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import ar.edu.unlu.sistemas.p2p.business.index.IndexController;
import ar.edu.unlu.sistemas.p2p.business.util.Indexer;
import ar.edu.unlu.sistemas.p2p.business.vo.TermFrecuencyVO;
import ar.edu.unlu.sistemas.p2p.business.vo.WordVO;

public class FileController {
	
	private static FileController INSTANCE;
	
	public IndexController index;
	
	public static FileController geInstance() {
		if (INSTANCE == null) {
			INSTANCE = new FileController();
		}
		return INSTANCE;
	}
	
	private FileController() {
		this.setIndex(IndexController.getInstance());
	}
	
	private IndexController getIndex() {
		return index;
	}

	public synchronized void setIndex(IndexController index) {
		this.index = index;
	}
	
	public synchronized int addQuery(String query) {
		int queryId = -1;
		queryId = this.getIndex().insertQueryImpl(query);
		String queryName = this.getIndex().findDocumentById(queryId).getName();
		try {
			HashMap<String,TermFrecuencyVO> terms = Indexer.indexQuery(query);
			this.insertTfs(terms, queryName);
		} catch (UnsupportedEncodingException uee) {

		}
		return queryId;
	}
	
	public synchronized void addFile(FileReader fr, String fileName) {
		if (this.getIndex().findDocumentByName(fileName) == null) {
			this.getIndex().insertDocImpl(fileName);
			try {
				HashMap<String,TermFrecuencyVO> terms = Indexer.createIndexFromFile(fr);
				this.insertTfs(terms, fileName);
			} catch (FileNotFoundException fne) {

			} catch (IOException ioe) {

			}

		}
	}
	
	private void insertTfs(HashMap<String,TermFrecuencyVO> terms, String docName) {
		String key;
		TermFrecuencyVO tfVO;
		Collection<WordVO> words = this.getIndex().findWordsByNames(terms.keySet());
		Iterator<String> keys = terms.keySet().iterator();
		while (keys.hasNext()) {
			key = keys.next();
			tfVO = terms.get(key);
			if (!words.contains(tfVO.getWord())) {
				this.getIndex().insertWord(tfVO.getWord().getName());
			}
			this.getIndex().insertTf(docName,key,tfVO.getValue());
		}
	}
	
}
